<template>
  <div>
    <div v-if="flag">
      <!--引用表格-->
      <BasicTable @register="registerTable" :rowSelection="rowSelection">
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
      <!-- 表单区域 -->
      <SchoolAssignmentRecordsModal @register="registerModal" @success="handleSuccess"></SchoolAssignmentRecordsModal>
    </div>
    <div class="noRecord" v-else>
      <img :src="EmptyImg" />
      <span>还没有学生上传作业</span>
    </div>
  </div>
</template>

<script lang="ts" name="record-schoolAssignmentRecords" setup>
  import { ref, reactive, computed, unref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import axios from 'axios';
  import { useListPage } from '/@/hooks/system/useListPage';
  import SchoolAssignmentRecordsModal from './components/assignScoreModel.vue';
  import { columns, searchFormSchema, superQuerySchema } from './assignScore.data.ts';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './assignScore.api.ts';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import EmptyImg from '@/assets/images/empty_new.png';
  import { getFileName } from '/@/utils/common/file';
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  const flag = ref(true);
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      // title: 'school_assignment_records',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'school_assignment_records',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }
  const handleDownload = async (record: Recordable) => {
    // 假设这是从后端获取的文件路径
    const fileUrl = record.assignmentPath;
    const filename = getFileName(fileUrl);

    try {
      const response = await axios.get(fileUrl, {
        responseType: 'blob', // 指定响应类型为 blob
      });
      console.log(response, 'resrsr');
      const blob = response.data;
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename; // 设置下载文件名
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('下载失败:', error);
    }
  };

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    if (record.status == '0') {
      return [
        {
          label: '下载',
          onClick: handleDownload.bind(null, record),
        },
        {
          label: '作业打分',
          onClick: handleEdit.bind(null, record),
        },
      ];
    } else {
      return [
        {
          label: '下载',
          onClick: handleDownload.bind(null, record),
        },
        {
          label: '查看',
          onClick: handleDetail.bind(null, record),
        },
      ];
    }
  }
  /**
   * 下拉操作栏
   */
  /*  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'record:school_assignment_records:delete',
      },
    ];
  } */
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
  .noRecord {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0 auto;
    img {
      width: 400px;
      height: 400px;
    }
    span {
      color: #000000;
      font-size: 20px;
    }
  }
</style>
